package pers.amos.edu.service;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import pers.amos.edu.common.RedisKeyConstant;
import pers.amos.edu.exception.EducationException;
import pers.amos.edu.exception.ExceptionEnum;
import pers.amos.edu.mapper.SchoolMapper;
import pers.amos.edu.pojo.School;
import tk.mybatis.mapper.entity.Example;

import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;

/**
 * @author amos wong
 * @create 2020-02-01 19:08
 */

@Service
public class SchoolService {

    @Autowired
    private SchoolMapper schoolMapper;

    @Autowired
    private RedisTemplate redisTemplate;

    public List<School> getSchoolList(String region, String openId) {
        List<LinkedHashMap<String, Object>> schoolMapList = redisTemplate.opsForList().range(RedisKeyConstant.SCHOOL_REGION_KEY + region, 0, -1);
        List<School> schoolList = new ArrayList<>();
        schoolMapList.forEach(schoolMap -> {
            School school = new School();
            Integer id = (Integer) schoolMap.get("id");
            String name = (String) schoolMap.get("name");
            school.setId(id);
            school.setName(name);
            school.setRegion(region);
            if (StringUtils.isEmpty(openId)) {
                school.setCollectionStatus(0);
            } else {
                Boolean isMember = redisTemplate.opsForSet().isMember(RedisKeyConstant.USER_COLLECT_SCHOOL_KEY + openId, school.getId());
                if (isMember) {
                    school.setCollectionStatus(1);
                }
            }
            schoolList.add(school);
        });
        return schoolList;
    }

    public List<School> searchSchool(String name, String openId) {
        Example example = new Example(School.class, true, false);
        Example.Criteria criteria = example.createCriteria();
        criteria.orLike("name", "%" + name + "%");
        List<School> schoolList = schoolMapper.selectByExample(example);
        if (CollectionUtils.isEmpty(schoolList)) {
            throw new EducationException(ExceptionEnum.NOT_FOUND);
        }
        if (StringUtils.isNotEmpty(openId)) {
            schoolList.forEach(school -> {
                Boolean isMember = redisTemplate.opsForSet().isMember(RedisKeyConstant.USER_COLLECT_SCHOOL_KEY + openId, school.getId());
                if (isMember) {
                    school.setCollectionStatus(1);
                }
            });
        }
        return schoolList;
    }
}
